<template>
  <div class="form-layout">
    <!--左侧导航-->
    <div class="nav-left">
      <customAnchor
        :itemList="[
          { name: 'box-base', title: '基础信息' },
          { name: 'box-dtl', title: '模版商品' },
        ]"
      />
    </div>
     <!--表单区域-->
     <div class="form-right" ref="formRight">
      <div id="box-base" class="box-title">基础信息</div>
      <customForm :data="form" :rules="propRules" ref="editForm" :disabled="propReadonly">
        <template #content>
          <customFormItem v-if="cpPackTypeIsDis" disabled label="模板类型" name="packTypeName" :parent="_self" :form="form" />
          <customFormItem
            v-else
            label="模板类型" name="packTypeId" :parent="_self" :form="form"
            :type="constCommon.formItemType.selectStatic.name"
            :config="{ options: packTypelist.filter(data => data.flagDisable === 0) }"
            @change="packTypeChange"
             />
          <customFormItem label="模板名称" name="name" :parent="_self" :form="form" />
          <customFormItem label="模板代码" name="code" :parent="_self" :form="form" />
          <customFormItem label="版本号" name="version" :parent="_self" :form="form"   :type="constCommon.formItemType.inputNumber.name"/>
          <customFormItem
            v-show="cpIsDesignateSp"
            label="供应商"
            name="supplierName"
            :parent="_self"
            :form="form"
            :readonly="true"
            :showSelectIcon="true"
            @focus="utilSelect.supplier(selectSupplier)"
            :disabled="cpHasDtl"
          />
          <customFormItem
            v-show="cpIsDesignateDept"
            label="科室"
            name="deptName"
            :parent="_self"
            :form="form"
            :readonly="true"
            :showSelectIcon="true"
            @focus="utilSelect.dept(selectDept)"
          />

          <customFormItem label="禁用" name="flagDisable" :parent="_self" :form="form"
                          :type="constCommon.formItemType.switch.name" />
          <customFormItem label="金额" name="amount" :parent="_self" :form="form"
           :type="constCommon.formItemType.inputNumber.name" disabled />

          <customFormItem label="备注" name="remark" :parent="_self" :form="form" />
        </template>
      </customForm>
      <div id="box-dtl" class="box-title">模版商品</div>
      <data-view
        propViewKey="base_pack_templet_item"
        :propInitData="form"
        :propParentData="propParent.viewFormData"
        ref="childDataView"
        :propsDisableDbClick="true"
        :propParentPage="_self"
        :propAutoFetchData="false"
        @extra-button-click="extraButtonClick"
        :propHideFlowSelect="true"
        @afterTableDataChange="afterTableDataChange"
        :propFlowKey="propParent.propFlowKey"
        :propNoEditRow="true"
        @customSelectFocus="customSelectFocus"
        @edit-input="editInput"
      />
    </div>

     <!--模版商品选择-->
     <tableDrawer
      ref="matrName"
      refName="matrName"
      viewKey="matr_select_inorder"
      loadForce
      title="请选择需要的商品"
      :queryWrapper="dtlRedqueryWrapper"
      :widthPer="80"
      :heightPx="-1"
      :widthPx="-1"
    />

  </div>
</template>

<script>
import customAnchor from '@/components/custom/form/customAnchor.vue'

export default {
  data() {
    return {
      form: {},
      viewData: {},
      dtlRedqueryWrapper: null,
      packTypelist: []
    }
  },
  computed: {
    // 是否有明细
    cpHasDtl() {
      const { countDtl, supplierId } = this.form
      return countDtl > 0 && this.strings.isNotBlank(supplierId)
    },
     // 模版类型是否禁用
     cpPackTypeIsDis() {
      const { packTypeId, id } = this.form
      if (!id) { // 新增
        return false
      }
      return this.getParams(packTypeId, 'flagDisable')
    },
    // 是否指定供应商
    cpIsDesignateSp() {
      const { packTypeId, id, flagDesignateSp } = this.form
      if (!id) { // 新增
        return flagDesignateSp === 1
      }
      return this.getParams(packTypeId, 'flagDesignateSp')
    },
    // 是否指定科室
    cpIsDesignateDept() {
      const { packTypeId, id, flagDesignateDept } = this.form
      if (!id) { // 新增
        return flagDesignateDept === 1
      }
      return this.getParams(packTypeId, 'flagDesignateDept')
    }
  },
  methods: {
    // 商品 新增、删除、修改后调用
    afterTableDataChange() {
      this.utils.refreshRefs(this)
    },
    loadDtl() {
      if (!this.$refs.childDataView) {
        return
      }
      let $newWrapper = this.$newWrapper()
      if (this.form.id) {
        $newWrapper.eq('packTempletId', this.form.id)
      } else {
        $newWrapper.ne(1, 1)
      }
      this.$refs.childDataView.setQueryWrapper($newWrapper)
    },

    //选择供应商事件
    selectSupplier(row) {
      this.$set(this.form, 'supplierId', row.id)
      this.$set(this.form, 'supplierName', row.name)
    },
    // 选择需求科室
    selectDept(row) {
      this.$set(this.form, 'deptId', row.id)
      this.$set(this.form, 'deptName', row.name)
    },

     // 添加商品列表
     _saveBatchItem(matrList) {
      this.utilVue.loadShow(true)
      const params = matrList.map(item => {
        return {packTempletId: this.form.id, matrId: item.id}
      })
      this.$ajax.post('/base/pack_templet_item/saveBatchUser', params).then((resp) => {
        this.utilVue.loadHide()
        if (resp.code == 0) {
          this.utilMessage.success(resp.msg)
          this.loadDtl()
          this.afterTableDataChange()
        }
      })
    },
      // 添加商品列表
     saveBatchItem(matrList) {
      //主单据未保存
      if(this.propParent.cpFormNew) {
        this.propParent.ocAsynSaveViewForm(() => {
          this._saveBatchItem(matrList)
        })
        return
      }
      this._saveBatchItem(matrList)
    },

    //获取模板类型
    getPackTypeList() {
      this.$ajax.get('/base/pack_type/list').then((resp) => {
        this.utilVue.loadHide()
        const {code, data} = resp
        if (code == 0) {
          const packTypeData = data.map(item => {
            const {id, id: value, name: label, flagDesignateDept, flagDesignateSp, flagDisable, type } = item
            return {id, label, value, id, flagDesignateDept, flagDesignateSp, flagDisable, type}
          })
          this.$set(this, 'packTypelist',packTypeData)
        }
      })
    },
    // 获取指定的参数值
    getParams(id, params) {
      const _Data = this.packTypelist.filter(item => item.id === id)
      return _Data.length && _Data[0][params] === 1
    },

    extraButtonClick({button}) {
      let {key: buttonKey} = button
      if (buttonKey == 'addBatch') { //批量添加
        this.propParent.ocAsynSaveViewForm(() => {
          if (this.strings.isNotBlank(this.form.supplierId)) {
            this.dtlRedqueryWrapper = this.$newWrapper()
            this.dtlRedqueryWrapper.eq('supplierId', this.form.supplierId)
          }
          this.$refs.matrName.show(this.saveBatchItem, true)
        })
      }
    },
    // 选择模板类型
    packTypeChange(value, item) {
      const { label, flagDesignateDept, flagDesignateSp } = item
      this.$set(this.form, 'packType', item.type)
      this.$set(this.form, 'packTypeId', value)
      this.$set(this.form, 'packTypeName', label)
      this.$set(this.form, 'supplierId', null)
      this.$set(this.form, 'supplierName', null)
      this.$set(this.form, 'deptId', null)
      this.$set(this.form, 'deptName', null)
      this.$set(this.form, 'flagDesignateDept', flagDesignateDept)
      this.$set(this.form, 'flagDesignateSp', flagDesignateSp)
    },
    // 自定义选择聚焦回调
    customSelectFocus(column, row) {
      // 包装名称
      if (column.name == 'packageUnit') {
        if (this.strings.isBlank(row.matrId)) {
          this.utilMessage.warning('请先选择商品')
          return
        }
        this.utilSelect.matrUnit(this.packageUnitSelect, row.matrId)
      }
    },
    // 单位选择后
    packageUnitSelect(row, refName) {
      // 当前选中行
      let currentRow = this.$refs.childDataView.getCurrentRow()
      this.$set(currentRow, 'packageUnit', row.packageUnit)
      this.$set(currentRow, 'packageRate', row.packageRate)
      this.$set(currentRow, 'skuQty', this.utilNum.toFixed(row.packageRate * currentRow.packageQty))
      this.$set(currentRow, 'amount', this.utilNum.toFixed(row.packagePrice * currentRow.packageQty))
    },

    //行编辑普通input框的修改事件，比如修改耗材包的数量后自动更新基本单位的数量
    editInput({row, column}) {
      if (column.property == 'packageQty') {
        this.$set(row, 'skuQty', this.utilNum.toFixed(row.packageRate * row.packageQty))
        this.$set(row, 'amount', this.utilNum.toFixed(row.skuPrice * row.skuQty))
      }
    },
  },
  created() {
    this.$emit('event-register', {
      validate: (callback) => {
        return this.$refs.editForm.validate(callback)
      },
      beforeSave: () => {
        if (this.cpIsDesignateSp && !this.form.supplierId) {
          this.utilMessage.error('该模板必须指定供应商')
          return false
        }
        if (this.cpIsDesignateDept && !this.form.deptId) {
          this.utilMessage.error('该模板必须指定科室')
          return false
        }
        this.$emit('data-callback', this.form)
        return true
      },
      afterMove: (formData, initData) => {
        this.form = global.utils.jsonClone(formData)
        this.getPackTypeList()
         // 新增，设置默认值
        if (!formData.id) {
          this.$set(this.form, 'version', '1.0')
          this.$set(this.form, 'flagDisable', 0)

        }
        this.loadDtl()
      },
      afterSave: () => {
        this.$refs.childDataView.propParentPage.$emit('refresh-row')
      },
      beforeDelete: () => {
        return true
      },
      afterDelete: () => {
      },
      beforeFlow: (flowButtonKey) => {
        return true
      },
      afterFlow: (flowButtonKey) => {
      },
      beforeClose: () => {
        return true
      }
    })
  },
  props: {
    propParent: Object,
    propInitData: Object,
    propPrimaryKey: String,
    propDictionaries: Object,
    propCurrentRow: Object,
    propViewFormData: Object,
    propReadonly: Boolean,
    propStatus: String,
    propRules: Object,
    propFlowKey: Object
  },
  components: {
    customAnchor
  },
}
</script>
